'use strict';
angular.module('clientApp')
.directive('ajoutervol', function($filter, flightAPI, ngToast) {
    return {
        restrict : 'E',
        scope : {
            volAdded : '='
        },
        link : function($scope) {
			$scope.format = 'dd/MM/yyyy';
			$scope.sendFormat = 'yyyy-MM-dd-HH-mm';
			$scope.hstep = 1;
			$scope.mstep = 1;
			$scope.ismeridian = false;
			$scope.IHeureDep = new Date();
			$scope.IHeureArr = new Date();
			  
			/*$scope.dtdepToday = function() {
				$scope.dtdep = Date.now();
			};
			$scope.dtdepToday();
			$scope.minDate = $scope.dtdep;*/
			
			$scope.open = function($event, opened) {
			    $event.preventDefault();
			    $event.stopPropagation();
				$scope[opened] = true;
			};
			
			$scope.dateOptions = {
				formatYear: 'yy',
				startingDay: 1
			};
        	  
        	$scope.ajoutvol = function() {
        		var vol = {};
        		vol.name = $scope.IName;
        		vol.departureTown = $scope.IVilleDep;
        		vol.arrivalTown = $scope.IVilleDest;
        		vol.departureTime = new Date(
					$scope.dtdep.getFullYear(),
					$scope.dtdep.getMonth(),
					$scope.dtdep.getDate(),
					$scope.IHeureDep.getHours(),
					$scope.IHeureDep.getMinutes()
				);
        		vol.departureTime = $filter('date')(vol.departureTime, $scope.sendFormat);
        		vol.arrivalTime = new Date(
					$scope.dtarr.getFullYear(),
					$scope.dtarr.getMonth(),
					$scope.dtarr.getDate(),
					$scope.IHeureArr.getHours(),
					$scope.IHeureArr.getMinutes()
				);
        		vol.arrivalTime = $filter('date')(vol.arrivalTime, $scope.sendFormat);
        		
        		flightAPI.add(vol)
        		.success(function(data) {
        			ngToast.create({
    					content: 'Le vol a bien été ajouté',
    					className: 'success'
    				});
        			console.log(data);
        			$scope.volAdded = data;
        			
        			delete $scope.IName;
             		delete $scope.IVilleDep;
             		delete $scope.IVilleDest;
             		delete $scope.dtdep;
     				$scope.IHeureDep = new Date();
             		delete $scope.dtarr;
     				$scope.IHeureArr = new Date();
            	})
            	.error(function() {
    				ngToast.create({
    					content: 'Erreur de communication avec le serveur',
    					className: 'danger'
    				});
    			});
        	};
        },
        templateUrl : 'views/directiveAjoutVol.html',
        replace : true
    };
});